package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请办理入住
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.判断老人是否已入住，如果已入住抛出异常
        //分析：根据身份证号查询和状态为0,1,2,3,4查询老人，如果有数据说明老人已入住
        LambdaQueryWrapper<Elder> elderQueryWrapper = Wrappers.lambdaQuery();
        elderQueryWrapper.eq(Elder::getIdCardNo,dto.getCheckInElderDto().getIdCardNo())
                .in(Elder::getStatus,0,1,2,3,4);
        Elder elderDb = elderMapper.selectOne(elderQueryWrapper);
        if(ObjectUtil.isNotEmpty(elderDb)){
            throw new BaseException("老人已入住，无法办理重新入住");
        }
        //2.更新床位状态为已入住
        //分析：根据床位id查询床位对象，将状态更新已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增或更新老人（对已经离开后又回来入住的老人需要更新，否则插入）
        Elder elder = insertOrUpdateElder(dto.getCheckInElderDto(),bed);

        //4.新增签约办理（合同数据）
        insertContract(dto,elder);

        //5.新增入住记录
        CheckIn checkIn = insertCheckInInfo(dto,elder);

        //6.新增入住配置
        insertCheckInConfig(checkIn.getId(), dto);
    }

    /**
     * 新增入住配置
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    //新增入住记录
    private CheckIn insertCheckInInfo(CheckInApplyDto dto,Elder elder) {

        //1.将checkInConfigDto封装给CheckIn对象
        CheckIn checkIn = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckIn.class);

        //2.补全数据
        //老人id
        checkIn.setElderId(elder.getId());
        //老人名字
        checkIn.setElderName(elder.getName());
        //老人身份证号
        checkIn.setIdCardNo(elder.getIdCardNo());
        //床位号
        checkIn.setBedNumber(elder.getBedNumber());
        //状态为0
        checkIn.setStatus(0);
        //备注：家属对象列表的json字符串
        String json = JSON.toJSONString(dto.getElderFamilyDtoList());
        checkIn.setRemark(json);

        //3.插入数据库
        baseMapper.insert(checkIn);

        return checkIn;
    }

    //新增签约办理（合同数据）
    private void insertContract(CheckInApplyDto checkInApplyDto,Elder elder) {
        //1.将checkInContractDto封装成Contract合同对象
        Contract contract = BeanUtil.toBean(checkInApplyDto.getCheckInContractDto(), Contract.class);

        //2.补全数据
        //老人id
        contract.setElderId(elder.getId());
        //老人名字
        contract.setElderName(elder.getName());
        //合同编号
        String contractNumber = "HT"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNumber);
        //合同开始日期
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        //合同结束日期
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        //合同状态，判断开始日期是否在当前日期的前面，是返回0未生效，否则返回1已生效
        Integer status = contract.getStartDate().isBefore(LocalDateTime.now())?0:1;
        contract.setStatus(status);

        //3.插入数据库
        contractMapper.insert(contract);
    }

    //更新或新增老人数据
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto,Bed bed) {
        //1.查询已退住的老人数据
        LambdaQueryWrapper<Elder> elderQueryWrapper = Wrappers.lambdaQuery();
        elderQueryWrapper.eq(Elder::getStatus,5);
        elderQueryWrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        Elder elderDb = elderMapper.selectOne(elderQueryWrapper);
        //将checkInElderDto的数据封装给elder对象(最新老人数据)
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);//将前端传递过来的最新老人数据赋值给elder对象
        //补全信息（前端没有传递的）
        //状态为1
        elder.setStatus(1);
        //床位id
        elder.setBedId(bed.getId());
        //床位编号
        elder.setBedNumber(bed.getBedNumber());

        if(elderDb!=null) {
            //2.有老人数据，执行更新
            elder.setId(elderDb.getId());//将已有老人id封装给elder对象
            elderMapper.updateById(elder);
        }else {
            //3.没有老人数据，插入
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        // 准备结果对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 1.设置入住配置响应信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        BeanUtils.copyProperties(checkIn, checkInConfigVo);

        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        // 2.设置老人响应信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        // 获取老人ID
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectById(elderId);
        BeanUtils.copyProperties(elder, checkInElderVo);
        // 从身份证号中获取老人的年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        // 3.设置家属响应信息
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);

        // 4.设置签约办理响应信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elderId));
        checkInDetailVo.setContract(contract);

        // 5.返回结果
        return checkInDetailVo;
    }
}
